/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.lock;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class GenericLockManager implements LockManager{

	private Map<String, Map<String, Element>> lockMap = new HashMap<String, Map<String, Element>>();
	private LockMapCleaner lockMapCleaner;
	private long cleanFrequencyInMinute;   
	
	public GenericLockManager() {
		this(30);
	}
	
	public GenericLockManager(long cleanFrequencyInMinute) {
		this.cleanFrequencyInMinute = (cleanFrequencyInMinute * 60 * 1000);
	}
	
	public void initiate() throws Exception {
		lockMapCleaner = new LockMapCleaner(cleanFrequencyInMinute, lockMap);
		new Thread(lockMapCleaner).start();
	}
	
	public Lock getLock(String clazz, String key){
		if(!lockMap.containsKey(clazz)){
			synchronized (lockMap) {
				if(!lockMap.containsKey(clazz)){
					lockMap.put(clazz, new HashMap<String, Element>());					
				}
			}
		}
		Map<String, Element> elementMap = lockMap.get(clazz);
		synchronized (elementMap) {
			if(elementMap.containsKey(key)){
				return elementMap.get(key).getLock();
			}
			ReentrantLock lock = new ReentrantLock(true);
			elementMap.put(key, new Element(lock));
			return lock;
		}
	}
	
	public void shutdown(){
		if(lockMapCleaner != null){
			lockMapCleaner.setActive(false);
		}
		synchronized (lockMap) {
			lockMap.clear();			
		}
	}
	
	private static class Element{
		private long timestamp;
		private Lock lock;
		public Element(Lock lock) {
			timestamp = System.currentTimeMillis();
			this.lock = lock;
		}
		public long getTimestamp() {
			return timestamp;
		}
		public Lock getLock() {
			timestamp = System.currentTimeMillis();
			return lock;
		}
	}
	
	private static class LockMapCleaner implements Runnable{
		private volatile boolean active;
		private long cleanFrequencyInMinute; 
		private Map<String,Map<String, Element>> lockMap;
		public LockMapCleaner(long cleanFrequencyInMinute, Map<String, Map<String, Element>> lockMap) {
			this.cleanFrequencyInMinute = cleanFrequencyInMinute;
			this.lockMap = lockMap;
			this.active = true;
		}
		public void run() {
			while(active){
				try {
					Thread.sleep(cleanFrequencyInMinute);
				} catch (Exception e) {}
				synchronized (lockMap) {
					if(lockMap.size() > 0){
						long currentTimestamp = System.currentTimeMillis();
						for (Iterator<String> iterator = lockMap.keySet().iterator(); iterator.hasNext();) {
							Map<String, Element> elementMap = lockMap.get(iterator.next());
							synchronized (elementMap) {
								if(elementMap.size() > 0){
									for (Iterator<String> elementMapIterator = elementMap.keySet().iterator(); elementMapIterator.hasNext();) {
										if( (currentTimestamp - cleanFrequencyInMinute) > elementMap.get(elementMapIterator.next()).getTimestamp() ){
											elementMapIterator.remove();
										}
									}									
								}									
							}
						}
					}					
				}
			}
		}
		public void setActive(boolean active) {
			this.active = active;
		}
	}
}